yu'an'yanuanyang<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const goToHome = () => {
  router.push('/home')
}
const knowledgeBase = ref([
 
])

const newFile = ref('')
const selectedFile = ref<File | null>(null)
const currentViewingFile = ref<any | null>(null)
const query = ref('')
const conversationId = ref<string>('')

const generateConversationId = () => {
  // 随机生成8位数字的会话ID并返回，要求必须是纯数字
  return Math.random().toString().slice(2, 10);
};

const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files.length > 0) {
    selectedFile.value = input.files[0]
    newFile.value = selectedFile.value.name
    conversationId.value = generateConversationId()
    uploadFile()
  }
}

const uploadFile = async () => {
  if (selectedFile.value) {
    const fileName = selectedFile.value.name;
    const extension = fileName.split('.').pop()?.toLowerCase() || '';
    const isPdf = extension === 'pdf';
    
    const reader = new FileReader();
    reader.onload = async (e) => {
      const content = e.target?.result as string;
      const newFileObj = {
        id: Date.now(),
        name: fileName,
        status: '处理中',
        content: content,
        fileType: extension
      };
      knowledgeBase.value.push(newFileObj);
      
      // 调用后端上传文件接口，将会话ID作为参数传递
      try {
        const formData = new FormData();
        formData.append('file', selectedFile.value as File);
        console.log('会话ID',conversationId.value)
        const response = await fetch(`http://localhost:8080/ai/pdf/upload/${conversationId.value}`, {
          method: 'POST',
          body: formData
        });
        
        if (response.ok) {
          console.log('文件上传成功');
          newFileObj.status = '已处理';
        } else {
          console.error('文件上传失败');
          newFileObj.status = '上传失败';
        }
      } catch (error) {
        console.error('上传文件时发生错误:', error);
        newFileObj.status = '上传失败';
      }
      
      // 清空选择的文件
      selectedFile.value = null;
      newFile.value = '';
    };
    
    // 读取文件内容
    if (isPdf) {
      reader.readAsDataURL(selectedFile.value);
    } else {
      reader.readAsText(selectedFile.value);
    }
  }
}

const searchKnowledge = async () => {
  if (query.value.trim()) {
    // 这里可以添加搜索知识库的逻辑
    console.log('搜索知识库:', query.value)
    console.log('会话ID',conversationId.value)
    
    try {
      const response = await fetch(`http://localhost:8080/ai/pdf/chat?prompt=${encodeURIComponent(query.value)}&conversationId=${conversationId.value}`, {
        method: 'POST'
      });
      const text = await response.text();
      
      if (response.ok) {
        let data;
        try {
          data = JSON.parse(text);
        } catch (parseError) {
          data = { content: text };
        }
        console.log('查询结果:', data.content);
        // 这里可以添加处理查询结果的逻辑
        currentViewingFile.value = {
          id: Date.now(),
          name: '查询结果',
          status: '已处理',
          content: data.content,
          fileType: 'text'
        };
        query.value = '';
      } else {
        console.error('查询请求失败:', text);
      }
    } catch (error) {
      console.error('查询失败:', error)
      // 这里可以添加处理查询失败的逻辑
    }
    
    query.value = '';
  }
}

const viewFile = (file: any) => {
  currentViewingFile.value = file
  console.log('查看文件:', file)
  // 这里可以添加查看文件的逻辑
}


</script>

<template>
  <div class="rag-container">
    <div class="rag-header">
      <h1 @click="goToHome" style="color: red; cursor: pointer;">RAG 个人知识库</h1>
      <p>构建个性化的知识库，支持自由对话</p>
    </div>
    
    <div class="upload-section">
      <h2>上传文件</h2>
      <div class="upload-input">
        <input 
          :value="newFile" 
          type="text" 
          placeholder="选择文件" 
          readonly
        />
        <input type="file" @change="handleFileChange" style="display: none" />
        <button @click="$event.target.previousElementSibling.click()">上传</button>
      </div>
    </div>
    
    <div class="knowledge-base">
      <h2>知识库文件</h2>
      <div class="file-list">
        <div 
          v-for="file in knowledgeBase" 
          :key="file.id"
          class="file-item"
        >
          <span class="file-name">{{ file.name }}</span>
          <button class="view-button" @click="viewFile(file)">查看</button>
        </div>
      </div>
    </div>
    
    <div v-if="currentViewingFile" class="file-content">
      <h3>查看文件: {{ currentViewingFile.name }}</h3>
      <div v-if="currentViewingFile.fileType === 'pdf'">
        <iframe 
          :src="currentViewingFile.content"
          style="width: 100%; height: 500px; border: none;"
        ></iframe>
      </div>
      <pre v-else>{{ currentViewingFile.content }}</pre>
      <button @click="currentViewingFile = null">关闭</button>
    </div>
    
    <div class="query-section">
      <h2>查询知识库</h2>
      <div class="query-input">
        <input 
          v-model="query" 
          type="text" 
          placeholder="询问关于您的知识库..." 
          @keyup.enter="searchKnowledge"
        />
        <button @click="searchKnowledge">查询</button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.rag-container {
  width: 100%;
  min-height: 100vh;
  margin: 0 auto;
  padding: 2rem;
  display: flex;
  flex-direction: column;
  box-sizing: border-box; // 确保padding不会影响整体尺寸
}

.rag-header {
  text-align: center;
  margin-bottom: 2rem;
  
  h1 {
    font-size: 2rem;
    color: red;
    margin-bottom: 0.5rem;
    cursor: pointer;
  }
  
  p {
    color: #666;
    font-size: 1rem;
  }
}

.upload-section,
.knowledge-base,
.query-section {
  margin-bottom: 2rem;
  
  h2 {
    font-size: 1.5rem;
    color: #333;
    margin-bottom: 1rem;
  }
}

.upload-input,
.query-input {
  display: flex;
  gap: 0.5rem;
  
  input {
    flex: 1;
    padding: 0.8rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 1rem;
    
    &:focus {
      outline: none;
      border-color: #409eff;
    }
  }
  
  button {
    padding: 0.8rem 1.5rem;
    background: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 1rem;
    
    &:hover {
      background: #337ecc;
    }
  }
}

.file-list {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 1rem;
  flex-grow: 1; // 让文件列表部分尽可能占据剩余空间
}

.file-item {
  display: flex;
  justify-content: space-between;
  padding: 0.8rem;
  background: #ffffff;
  border-radius: 4px;
  margin-bottom: 0.5rem;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.view-button {
  padding: 0.2rem 0.5rem;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8rem;
  
  &:hover {
    background: #337ecc;
  }
}

.file-content {
  margin-top: 2rem;
  padding: 1rem;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  h3 {
    margin-top: 0;
    color: #333;
  }
  
  pre {
    background: #f5f5f5;
    padding: 1rem;
    border-radius: 4px;
    overflow: auto;
    max-height: 400px;
    white-space: pre-wrap;
  }
  
  button {
    margin-top: 1rem;
    padding: 0.5rem 1rem;
    background: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    
    &:hover {
      background: #337ecc;
    }
  }
}
</style>